<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use hehe\Str;
use think\facade\Db;
use think\middleware\FormTokenCheck;

use ba\Filesystem;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;

/**
 *
 */
class Merge extends Backend {
    /**
     * Goods模型对象
     * @var object
     * @phpstan-var \app\admin\model\goods\Goods
     */
    protected object $orderModel;
    protected object $orderGoodsModel;



    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['name', 'brand.name'];

    public function initialize(): void {
        parent::initialize();
        $this->orderGoodsModel = new \app\admin\model\order\OrderGoods();
    }

    /**
     * 修改订单商品的尺码
     */
    public function updateSize(): void{
        $param = $this->request->param();
        $suborder = db::name('order_goods')->where(['id' => $param['id']])->find();
        if($suborder['status'] != 0 && !empty($suborder['size'])) $this->error('当前订单状态禁止修改尺码');
        $update = [
            'size' => $param['val'],
            'update_time' => $this->timestamp
        ];
        $result = db::name('order_goods')->where(['id' => $param['id']])->update($update);

        if($result){
            $this->success();
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 操作记录
     */
    public function shipmentStatusLogindex(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 修改订单商品的颜色
     */
    public function updateColor(): void{
        $param = $this->request->param();
        $suborder = db::name('order_goods')->where(['id' => $param['id']])->find();
        if($suborder['status'] != 0 && !empty($suborder['color'])) $this->error('当前订单状态禁止修改颜色');
        $update = [
            'color' => $param['val'],
            'update_time' => $this->timestamp
        ];
        $result = db::name('order_goods')->where(['id' => $param['id']])->update($update);

        if($result){
            $this->success();
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 修改订单商品采购价格
     */
    public function updatePurchasePrice(): void{
        $param = $this->request->param();
        $suborder = db::name('order_goods')->where(['id' => $param['id']])->find();
        if($suborder['status'] != 0) $this->error('当前订单状态禁止修改价格');

        $goods = db::name('goods')->where(['id' => $suborder['goods_id']])->find();

        if($param['val'] <= $goods['supply_price']) $this->error('DC价格必须大于商品的采购价格');

        $total_price = $param['val'] * $suborder['num'];

        $update = [
            'total_price' => $total_price,
            'purchase_price' => $param['val'],
            'update_time' => $this->timestamp
        ];
        $result = db::name('order_goods')->where(['id' => $param['id']])->update($update);

        if($result){
            $this->success('', [
                'total_price_text' => number_format($total_price),
                'purchase_price_text' => number_format($param['val'])
            ]);
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 修改订单商品数量
     */
    public function updateOrderNum(): void{
        $param = $this->request->param();
        $suborder = db::name('order_goods')->where(['id' => $param['id']])->find();
        if($suborder['status'] != 0) $this->error('当前订单状态禁止修改数量');

        $total_price = $param['num'] * $suborder['purchase_price'];

        $update = [
            'total_price' => $total_price,
            'num' => $param['num'],
            'update_time' => $this->timestamp
        ];
        $result = db::name('order_goods')->where(['id' => $param['id']])->update($update);

        if($result){
            $this->success('', [
                'total_price_text' => number_format($total_price)
            ]);
        }else{
            $this->error('操作失败');
        }

        print_r($param);die;
    }

    /**
     * 删除子订单备注
     */
    public function delNote(): void{
        $id = $this->request->param('id');
        db::name('suborder_note')->where(['id' => $id])->delete();
        $this->success();
    }
    /**
     * 添加子订单备注
     */
    public function addNote(): void {
        $insert = $this->request->param();
        if(empty($insert['content'])) $this->error('备注内容不能为空');
        $insert['create_time'] = $this->timestamp;
        $insert['admin_id'] = $this->auth->id;
        $suborder_id = db::name('suborder_note')->insertGetId($insert);
        if($suborder_id){
            $this->success('', [
                'id' => $suborder_id,
                'content' => $insert['content'],
                'admin' => [
                    'username' => $this->auth->username
                ]

            ]);
        }else{
            $this->error();
        }
        print_r($insert);die;
    }

    /**
     * 更新出货状态
     */
    public function updateStatus(): void {
        $param = $this->request->param();
//        print_r($param);die;
        $split = false; // 是否拆分订单
        Db::startTrans();
        try{
            $order_goods = db::name('order_goods')->where(['id' => $param['order_goods_id']])->find();
            $order = db::name('order')->where(['id' => $order_goods['order_id']])->find();
            $user = db::name('user')->where(['id' => $order['user_id']])->find();

            if($param['current_status'] == 1){ // 修改为已下单
                // 扣除用户的预备金
                db::name('user')->where(['id' => $order['user_id']])->setDec('money', $order_goods['total_price']);
                // 记录用户的预备金变动日志
                $money_log_insert = [
                    'user_id' => $user['id'],
                    'money' => $order_goods['total_price'],
                    'before' => $user['money'],
                    'after' => $user['money'] - $order_goods['total_price'],
                    'memo' => '下单扣除',
                    'create_time' => $this->timestamp
                ];
                db::name('user_money_log')->insert($money_log_insert);
                $insert_record = [  // 状态更改记录
                    'order_goods_id' => $param['order_goods_id'],
                    'before_change' => $param['status'],
                    'after_change' => $param['current_status'],
                    'create_time' => $this->timestamp,
                    'admin_id' => $this->auth->id,
                ];
                db::name('order_goods_status_record')->insert($insert_record);
                // 修改原订单数据
                $update = [
                    'status' => $param['current_status'],
                    'update_time' => $this->timestamp
                ];
                $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
            }

            if($param['current_status'] == 2){ // 修改为现货状态
                if(empty($param['stock_split'])) $param['stock_split'] = $order_goods['num'];
                if($param['stock_split'] < 1) throw new \Exception('现货数量不能小于1');
                $param['stock_split'] = $param['stock_split'] > $order_goods['num'] ? $order_goods['num'] : $param['stock_split'];
                if($param['stock_split'] != $order_goods['num']){ // 现货与数量不一致, 需要拆分订单
                    $insert = [
                        'pid' => $param['order_goods_id'],
                        'order_id' => $order_goods['order_id'],
                        'goods_id' => $order_goods['goods_id'],
                        'color' => $order_goods['color'],
                        'size' => $order_goods['size'],
                        'num' => $param['stock_split'],
                        'place_order_time' => $order_goods['place_order_time'],
                        'total_price' => $param['stock_split'] * $order_goods['purchase_price'],
                        'purchase_price' => $order_goods['purchase_price'],
                        'status' => $param['current_status']
                    ];
                    $split_order_id = Db::name('order_goods')->insertGetId($insert); // 拆分订单
                    $split = true;





                    // 修改原订单数据
                    $update = [
                        'num' => $order_goods['num'] - $param['stock_split'],
                        'total_price' => ($order_goods['num'] - $param['stock_split']) * $order_goods['purchase_price'],
                        'update_time' => $this->timestamp
                    ];
                    $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
                }else{
                    $insert_record = [  // 状态更改记录
                        'order_goods_id' => $param['order_goods_id'],
                        'before_change' => $param['status'],
                        'after_change' => $param['current_status'],
                        'create_time' => $this->timestamp,
                        'admin_id' => $this->auth->id,
                    ];
                    db::name('order_goods_status_record')->insert($insert_record);
                    // 修改原订单数据
                    $update = [
                        'status' => $param['current_status'],
                        'update_time' => $this->timestamp
                    ];
                    $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
                }
            }

            if($param['current_status'] == 5){ // 修改为入库状态
                if(empty($param['storage_split'])) $param['storage_split'] = $order_goods['num'];
                if($param['storage_split'] < 1) throw new \Exception('入库数量不能小于1');
                $param['storage_split'] = $param['storage_split'] > $order_goods['num'] ? $order_goods['num'] : $param['storage_split'];
                if($param['storage_split'] != $order_goods['num']){ // 现货与数量不一致, 需要拆分订单
                    $insert = [
                        'pid' => $param['order_goods_id'],
                        'order_id' => $order_goods['order_id'],
                        'goods_id' => $order_goods['goods_id'],
                        'color' => $order_goods['color'],
                        'size' => $order_goods['size'],
                        'num' => $param['storage_split'],
                        'place_order_time' => $order_goods['place_order_time'],
                        'total_price' => $param['storage_split'] * $order_goods['purchase_price'],
                        'purchase_price' => $order_goods['purchase_price'],
                        'status' => $param['current_status']
                    ];
                    $split_order_id = Db::name('order_goods')->insertGetId($insert); // 拆分订单
                    $split = true;


                    // 修改原订单数据
                    $update = [
                        'num' => $order_goods['num'] - $param['storage_split'],
                        'total_price' => ($order_goods['num'] - $param['storage_split']) * $order_goods['purchase_price'],
                        'update_time' => $this->timestamp
                    ];
                    $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
                }else{
                    $insert_record = [  // 状态更改记录
                        'order_goods_id' => $param['order_goods_id'],
                        'before_change' => $param['status'],
                        'after_change' => $param['current_status'],
                        'create_time' => $this->timestamp,
                        'admin_id' => $this->auth->id,
                    ];
                    db::name('order_goods_status_record')->insert($insert_record);
                    // 修改原订单数据
                    $update = [
                        'status' => $param['current_status'],
                        'update_time' => $this->timestamp
                    ];
                    $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
                }
            }

            if($param['current_status'] == 6){ // 修改为韩国已发货
                if(empty($param['krw_split'])) $param['krw_split'] = $order_goods['num'];
                if($param['krw_split'] < 1) throw new \Exception('已发货数量不能小于1');
                $param['krw_split'] = $param['krw_split'] > $order_goods['num'] ? $order_goods['num'] : $param['krw_split'];
                if($param['krw_split'] != $order_goods['num']){ // 现货与数量不一致, 需要拆分订单
                    $insert = [
                        'pid' => $param['order_goods_id'],
                        'order_id' => $order_goods['order_id'],
                        'goods_id' => $order_goods['goods_id'],
                        'color' => $order_goods['color'],
                        'size' => $order_goods['size'],
                        'num' => $param['krw_split'],
                        'place_order_time' => $order_goods['place_order_time'],
                        'total_price' => $param['krw_split'] * $order_goods['purchase_price'],
                        'purchase_price' => $order_goods['purchase_price'],
                        'status' => $param['current_status']
                    ];
                    $split_order_id = Db::name('order_goods')->insertGetId($insert); // 拆分订单
                    $split = true;


                    // 修改原订单数据
                    $update = [
                        'num' => $order_goods['num'] - $param['krw_split'],
                        'total_price' => ($order_goods['num'] - $param['krw_split']) * $order_goods['purchase_price'],
                        'update_time' => $this->timestamp
                    ];
                    $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
                }else{
                    $insert_record = [  // 状态更改记录
                        'order_goods_id' => $param['order_goods_id'],
                        'before_change' => $param['status'],
                        'after_change' => $param['current_status'],
                        'create_time' => $this->timestamp,
                        'admin_id' => $this->auth->id,
                    ];
                    db::name('order_goods_status_record')->insert($insert_record);
                    // 修改原订单数据
                    $update = [
                        'status' => $param['current_status'],
                        'update_time' => $this->timestamp
                    ];
                    $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
                }
            }



            // 修改为退款状态
            if($param['current_status'] == '8-1' || $param['current_status'] == '8-2' || $param['current_status'] == '8-3'){

                // 增加用户的预备金
                db::name('user')->where(['id' => $order['user_id']])->setInc('money', $order_goods['total_price']);
                // 记录用户的预备金变动日志
                $money_log_insert = [
                    'user_id' => $user['id'],
                    'money' => $order_goods['total_price'],
                    'before' => $user['money'],
                    'after' => $user['money'] + $order_goods['total_price'],
                    'memo' => '订单退款返回预备金',
                    'create_time' => $this->timestamp
                ];
                db::name('user_money_log')->insert($money_log_insert);


                $insert_record = [  // 状态更改记录
                    'order_goods_id' => $param['order_goods_id'],
                    'before_change' => $param['status'],
                    'after_change' => $param['current_status'],
                    'create_time' => $this->timestamp,
                    'admin_id' => $this->auth->id,
                ];
                db::name('order_goods_status_record')->insert($insert_record);
                // 修改原订单数据
                $update = [
                    'status' => $param['current_status'],
                    'update_time' => $this->timestamp
                ];
                $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
            }

            // 修改为换货状态
            if($param['current_status'] == '9-1' || $param['current_status'] == '9-2' || $param['current_status'] == '9-3' || $param['current_status'] == '9-4'){
                $insert_record = [  // 状态更改记录
                    'order_goods_id' => $param['order_goods_id'],
                    'before_change' => $param['status'],
                    'after_change' => $param['current_status'],
                    'create_time' => $this->timestamp,
                    'admin_id' => $this->auth->id,
                ];
                db::name('order_goods_status_record')->insert($insert_record);
                // 修改原订单数据
                $update = [
                    'status' => $param['current_status'],
                    'update_time' => $this->timestamp
                ];
                $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
            }

            // 修改为待定状态
            if($param['current_status'] == 7){
                $insert_record = [  // 状态更改记录
                    'order_goods_id' => $param['order_goods_id'],
                    'before_change' => $param['status'],
                    'after_change' => $param['current_status'],
                    'create_time' => $this->timestamp,
                    'admin_id' => $this->auth->id,
                ];
                db::name('order_goods_status_record')->insert($insert_record);
                // 修改原订单数据
                $update = [
                    'status' => $param['current_status'],
                    'update_time' => $this->timestamp
                ];
                $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
            }
            // 修改为取消订单
            if($param['current_status'] == -1){
                if($order_goods['status'] != 0){
                    // 增加用户的预备金
                    db::name('user')->where(['id' => $order['user_id']])->setInc('money', $order_goods['total_price']);
                    // 记录用户的预备金变动日志
                    $money_log_insert = [
                        'user_id' => $user['id'],
                        'money' => $order_goods['total_price'],
                        'before' => $user['money'],
                        'after' => $user['money'] + $order_goods['total_price'],
                        'memo' => '取消订单返回预备金',
                        'create_time' => $this->timestamp
                    ];
                    db::name('user_money_log')->insert($money_log_insert);
                }


                // 状态更改记录
                $insert_record = [
                    'order_goods_id' => $param['order_goods_id'],
                    'before_change' => $param['status'],
                    'after_change' => $param['current_status'],
                    'create_time' => $this->timestamp,
                    'admin_id' => $this->auth->id,
                ];
                db::name('order_goods_status_record')->insert($insert_record);
                // 修改原订单数据
                $update = [
                    'status' => $param['current_status'],
                    'update_time' => $this->timestamp
                ];
                $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
            }

            if($param['current_status'] == 10){ // 修改为已提货
                if(empty($param['delivery_split'])) $param['delivery_split'] = $order_goods['num'];
                if($param['delivery_split'] < 1) throw new \Exception('已提货数量不能小于1');
                $param['delivery_split'] = $param['delivery_split'] > $order_goods['num'] ? $order_goods['num'] : $param['delivery_split'];
                if($param['delivery_split'] != $order_goods['num']){ // 现货与数量不一致, 需要拆分订单
                    $insert = [
                        'pid' => $param['order_goods_id'],
                        'order_id' => $order_goods['order_id'],
                        'goods_id' => $order_goods['goods_id'],
                        'color' => $order_goods['color'],
                        'size' => $order_goods['size'],
                        'num' => $param['delivery_split'],
                        'place_order_time' => $order_goods['place_order_time'],
                        'total_price' => $param['delivery_split'] * $order_goods['purchase_price'],
                        'purchase_price' => $order_goods['purchase_price'],
                        'status' => $param['current_status']
                    ];
                    $split_order_id = Db::name('order_goods')->insertGetId($insert); // 拆分订单
                    $split = true;

                    // 修改原订单数据
                    $update = [
                        'num' => $order_goods['num'] - $param['delivery_split'],
                        'total_price' => ($order_goods['num'] - $param['delivery_split']) * $order_goods['purchase_price'],
                        'update_time' => $this->timestamp
                    ];
                    $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
                }else{
                    $insert_record = [  // 状态更改记录
                        'order_goods_id' => $param['order_goods_id'],
                        'before_change' => $param['status'],
                        'after_change' => $param['current_status'],
                        'create_time' => $this->timestamp,
                        'admin_id' => $this->auth->id,
                    ];
                    db::name('order_goods_status_record')->insert($insert_record);
                    // 修改原订单数据
                    $update = [
                        'status' => $param['current_status'],
                        'update_time' => $this->timestamp
                    ];
                    $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
                }
            }

            if($param['current_status'] == 3){ // 修改为付款预定
                if(empty($param['pay_reserve_num_split'])) $param['pay_reserve_num_split'] = $order_goods['num'];
                if(empty($param['pay_reserve_day_split']) || $param['pay_reserve_day_split'] < 1) throw new \Exception('请输入正确的预定天数');
                if($param['pay_reserve_num_split'] < 1) throw new \Exception('已提货数量不能小于1');
                $param['pay_reserve_num_split'] = $param['pay_reserve_num_split'] > $order_goods['num'] ? $order_goods['num'] : $param['pay_reserve_num_split'];
                if($param['pay_reserve_num_split'] != $order_goods['num']){ // 拆分与总数量不一致, 需要拆分订单
                    $insert = [
                        'pid' => $param['order_goods_id'],
                        'order_id' => $order_goods['order_id'],
                        'goods_id' => $order_goods['goods_id'],
                        'color' => $order_goods['color'],
                        'size' => $order_goods['size'],
                        'num' => $param['pay_reserve_num_split'],
                        'place_order_time' => $order_goods['place_order_time'],
                        'total_price' => $param['pay_reserve_num_split'] * $order_goods['purchase_price'],
                        'purchase_price' => $order_goods['purchase_price'],
                        'status' => $param['current_status'],
                        'pay_reserve_day' => $param['pay_reserve_day_split'],
                        'pay_reserve_time' => $this->timestamp + ( $param['pay_reserve_day_split'] * 86400 )
                    ];
                    $split_order_id = Db::name('order_goods')->insertGetId($insert); // 拆分订单
                    $split = true;


                    // 修改原订单数据
                    $update = [
                        'num' => $order_goods['num'] - $param['pay_reserve_num_split'],
                        'total_price' => ($order_goods['num'] - $param['pay_reserve_num_split']) * $order_goods['purchase_price'],
                        'update_time' => $this->timestamp
                    ];
                    $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
                }else{
                    $insert_record = [  // 状态更改记录
                        'order_goods_id' => $param['order_goods_id'],
                        'before_change' => $param['status'],
                        'after_change' => $param['current_status'],
                        'create_time' => $this->timestamp,
                        'admin_id' => $this->auth->id,
                    ];
                    db::name('order_goods_status_record')->insert($insert_record);
                    // 修改原订单数据
                    $update = [
                        'status' => $param['current_status'],
                        'update_time' => $this->timestamp,
                        'pay_reserve_day' => $param['pay_reserve_day_split'],
                        'pay_reserve_time' => $this->timestamp + ( $param['pay_reserve_day_split'] * 86400 )
                    ];
                    $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
                }
            }

            if($param['current_status'] == 4){ // 修改为口头预定
                if(empty($param['verbal_reserve_num_split'])) $param['verbal_reserve_num_split'] = $order_goods['num'];
                if(empty($param['verbal_reserve_day_split']) || $param['verbal_reserve_day_split'] < 1) throw new \Exception('请输入正确的预定天数');
                if($param['verbal_reserve_num_split'] < 1) throw new \Exception('已提货数量不能小于1');
                $param['verbal_reserve_num_split'] = $param['verbal_reserve_num_split'] > $order_goods['num'] ? $order_goods['num'] : $param['verbal_reserve_num_split'];
                if($param['verbal_reserve_num_split'] != $order_goods['num']){ // 拆分与总数量不一致, 需要拆分订单
                    $insert = [
                        'pid' => $param['order_goods_id'],
                        'order_id' => $order_goods['order_id'],
                        'goods_id' => $order_goods['goods_id'],
                        'color' => $order_goods['color'],
                        'size' => $order_goods['size'],
                        'num' => $param['verbal_reserve_num_split'],
                        'place_order_time' => $order_goods['place_order_time'],
                        'total_price' => $param['verbal_reserve_num_split'] * $order_goods['purchase_price'],
                        'purchase_price' => $order_goods['purchase_price'],
                        'status' => $param['current_status'],
                        'verbal_reserve_day' => $param['verbal_reserve_day_split'],
                        'verbal_reserve_time' => $this->timestamp + ( $param['verbal_reserve_day_split'] * 86400 )
                    ];
                    $split_order_id = Db::name('order_goods')->insertGetId($insert); // 拆分订单
                    $split = true;

                    // 修改原订单数据
                    $update = [
                        'num' => $order_goods['num'] - $param['verbal_reserve_num_split'],
                        'total_price' => ($order_goods['num'] - $param['verbal_reserve_num_split']) * $order_goods['purchase_price'],
                        'update_time' => $this->timestamp
                    ];
                    $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
                }else{
                    $insert_record = [  // 状态更改记录
                        'order_goods_id' => $param['order_goods_id'],
                        'before_change' => $param['status'],
                        'after_change' => $param['current_status'],
                        'create_time' => $this->timestamp,
                        'admin_id' => $this->auth->id,
                    ];
                    db::name('order_goods_status_record')->insert($insert_record);
                    // 修改原订单数据
                    $update = [
                        'status' => $param['current_status'],
                        'update_time' => $this->timestamp,
                        'verbal_reserve_day' => $param['verbal_reserve_day_split'],
                        'verbal_reserve_time' => $this->timestamp + ( $param['verbal_reserve_day_split'] * 86400 )
                    ];
                    $result = Db::name('order_goods')->where(['id' => $param['order_goods_id']])->update($update);
                }
            }

            if($split){
                // 写入拆分订单的状态更改记录
                $field = 'order_goods_id, before_change, after_change, create_time, admin_id';
                $order_goods_status_record = db::name('order_goods_status_record')->field($field)->where(['order_goods_id' => $param['order_goods_id']])->select();
                $order_goods_status_record_insert = [];
                foreach($order_goods_status_record as $val){
                    $val['order_goods_id'] = $split_order_id;
                    $order_goods_status_record_insert[] = $val;
                }
                $order_goods_status_record_insert[] = [
                    'order_goods_id' => $split_order_id,
                    'before_change' => $param['status'],
                    'after_change' => $param['current_status'],
                    'create_time' => $this->timestamp,
                    'admin_id' => $this->auth->id,
                ];
                db::name('order_goods_status_record')->insertAll($order_goods_status_record_insert);
            }


            db::commit();
        }catch(\Exception $e){
            db::rollback();
            $this->error($e->getMessage());
        }
        if($result){

            $field = "b.name brand_name, g.cover goods_cover, u.username, g.name goods_name,
                    og.color, og.size, g.supply_price, g.price, og.num, og.total_price, og.purchase_price, og.status, 
                    og.id order_goods_id, og.pay_reserve_day, og.verbal_reserve_day, b.id brand_id, b.outstation_id";
            $row = $this->orderGoodsModel->alias('og')->field($field) // 子订单
                ->leftJoin('order o', 'og.order_id = o.id') // 订单
                ->leftJoin('user u', 'o.user_id = u.id') // 用户
                ->leftJoin('goods g', 'og.goods_id = g.id') // 商品
                ->leftJoin('goods_brand b', 'g.goods_brand_id=b.id') //品牌
                ->append(['status_text', 'purchase_price_text', 'price_text', 'supply_price_text', 'total_price_text'])
                ->where(['og.id' => $param['order_goods_id']])
                ->order('og.order_id desc')
                ->find();
            $split_order = false;
            if(isset($split_order_id)){
                $split_order = $this->orderGoodsModel->alias('og')->field($field) // 子订单
                ->leftJoin('order o', 'og.order_id = o.id') // 订单
                ->leftJoin('user u', 'o.user_id = u.id') // 用户
                ->leftJoin('goods g', 'og.goods_id = g.id') // 商品
                ->leftJoin('goods_brand b', 'g.goods_brand_id=b.id') //品牌
                ->append(['status_text', 'purchase_price_text', 'price_text', 'supply_price_text', 'total_price_text'])
                    ->where(['og.id' => $split_order_id])
                    ->order('og.order_id desc')
                    ->find();
            }



            $this->success('', [
                'row' => $row,
                'split_order' => $split_order
            ]);
        }else{
            $this->error();
        }
    }

    /**
     * 撤回出货状态
     */
    public function withdrawStatus(){
        $param = $this->request->param();
        $record = db::name('order_goods_status_record')->where(['order_goods_id' => $param['order_goods_id']])->order('id desc')->find();
        if(!$record) $this->error('该订单没有更改状态的记录');
        $order_goods = db::name('order_goods')->where(['id' => $param['order_goods_id']])->find();
        $order = db::name('order')->where(['id' => $order_goods['order_id']])->find();
        $user = db::name('user')->where(['id' => $order['user_id']])->find();
        db::startTrans();
        try{

            if($record['before_change'] == 0 && $order_goods['status'] != -1){ // 撤回为准备下单状态 增加用户预备金
                // 增加用户的预备金
                db::name('user')->where(['id' => $order['user_id']])->setInc('money', $order_goods['total_price']);
                // 记录用户的预备金变动日志
                $money_log_insert = [
                    'user_id' => $user['id'],
                    'money' => $order_goods['total_price'],
                    'before' => $user['money'],
                    'after' => $user['money'] + $order_goods['total_price'],
                    'memo' => '撤回订单已下单状态为准备下单，增加预备金',
                    'create_time' => $this->timestamp
                ];
                db::name('user_money_log')->insert($money_log_insert);
            }
            if($record['before_change'] == -1 && $order_goods['status'] != 0){ // 撤回为取消下单状态 增加用户预备金
                // 增加用户的预备金
                db::name('user')->where(['id' => $order['user_id']])->setInc('money', $order_goods['total_price']);
                // 记录用户的预备金变动日志
                $money_log_insert = [
                    'user_id' => $user['id'],
                    'money' => $order_goods['total_price'],
                    'before' => $user['money'],
                    'after' => $user['money'] + $order_goods['total_price'],
                    'memo' => '撤回为取消下单状态 增加预备金',
                    'create_time' => $this->timestamp
                ];
                db::name('user_money_log')->insert($money_log_insert);
            }
            if($record['before_change'] == '8-1' || $record['before_change'] == '8-2' || $record['before_change'] == '8-3'){ // 撤回为退款状态 增加用户预备金
                // 增加用户的预备金
                db::name('user')->where(['id' => $order['user_id']])->setInc('money', $order_goods['total_price']);
                // 记录用户的预备金变动日志
                $money_log_insert = [
                    'user_id' => $user['id'],
                    'money' => $order_goods['total_price'],
                    'before' => $user['money'],
                    'after' => $user['money'] + $order_goods['total_price'],
                    'memo' => '撤回为退款状态 增加预备金',
                    'create_time' => $this->timestamp
                ];
                db::name('user_money_log')->insert($money_log_insert);
            }
            if($record['before_change'] == 1 && $order_goods['status'] == 0){ // 修改为已下单状态 扣除用户预备金
                // 扣除用户的预备金
                db::name('user')->where(['id' => $order['user_id']])->setDec('money', $order_goods['total_price']);
                // 记录用户的预备金变动日志
                $money_log_insert = [
                    'user_id' => $user['id'],
                    'money' => $order_goods['total_price'],
                    'before' => $user['money'],
                    'after' => $user['money'] - $order_goods['total_price'],
                    'memo' => '撤回订单准备下单状态为已下单，扣除预备金',
                    'create_time' => $this->timestamp
                ];
                db::name('user_money_log')->insert($money_log_insert);
            }
            if($order_goods['status'] == -1 && $record['before_change'] != 0){ //撤回取消状态，扣除预备金
                // 扣除用户的预备金
                db::name('user')->where(['id' => $order['user_id']])->setDec('money', $order_goods['total_price']);
                // 记录用户的预备金变动日志
                $money_log_insert = [
                    'user_id' => $user['id'],
                    'money' => $order_goods['total_price'],
                    'before' => $user['money'],
                    'after' => $user['money'] - $order_goods['total_price'],
                    'memo' => '撤回取消订单状态，扣除预备金',
                    'create_time' => $this->timestamp
                ];
                db::name('user_money_log')->insert($money_log_insert);
            }
            if($order_goods['status'] == '8-1' || $order_goods['status'] == '8-2' || $order_goods['status'] == '8-3'){ //撤回退款状态，扣除预备金
                // 扣除用户的预备金
                db::name('user')->where(['id' => $order['user_id']])->setDec('money', $order_goods['total_price']);
                // 记录用户的预备金变动日志
                $money_log_insert = [
                    'user_id' => $user['id'],
                    'money' => $order_goods['total_price'],
                    'before' => $user['money'],
                    'after' => $user['money'] - $order_goods['total_price'],
                    'memo' => '撤回退款订单状态，扣除预备金',
                    'create_time' => $this->timestamp
                ];
                db::name('user_money_log')->insert($money_log_insert);
            }

            $where = [
                'id' => $param['order_goods_id']
            ];
            $update = [
                'status' => $record['before_change'],
                'update_time' => $this->timestamp
            ];
            db::name('order_goods')->where($where)->update($update);
            $insert_record = [
                'order_goods_id' => $param['order_goods_id'],
                'before_change' => $record['after_change'],
                'after_change' => $record['before_change'],
                'create_time' => $this->timestamp,
                'admin_id' => $this->auth->id,
            ];
            db::name('order_goods_status_record')->insert($insert_record);
            db::commit();
        }catch (\Exception $e){
            db::rollback();
            $this->error($e->getMessage());
        }
        $row = $this->orderGoodsModel->where(['id' => $param['order_goods_id']])->append(['status_text'])->find();
        $this->success('', $row);
    }

    /**
     * 合并订单数据列表
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);

        $field = "og.id, b.name brand_name, g.cover goods_cover, u.username, g.name goods_name,
                    og.color, og.size, g.supply_price, g.price, og.num, og.total_price, og.purchase_price, og.status, 
         og.id order_goods_id, og.pay_reserve_day, og.verbal_reserve_day, b.id brand_id, b.outstation_id";
        $where = [
            ['b.outstation_id', '=', $this->outstation['id']], // 只查询当前分站的订单
            ['o.status', '=', 1]
        ];
        $list = $this->orderGoodsModel->alias('og')
            ->with([
                'suborder_note' => function($query){ // 子订单备注
                    $query->with(['admin']);
                }, 'hasSubOrderGoods'
            ])->field($field) // 子订单
            ->leftJoin('order o', 'og.order_id = o.id') // 订单
            ->leftJoin('user u', 'o.user_id = u.id') // 用户
            ->leftJoin('goods g', 'og.goods_id = g.id') // 商品
            ->leftJoin('goods_brand b', 'g.goods_brand_id=b.id') //品牌
            ->where($where);

        $state = $this->request->param('state');

        $id = $this->request->param('id');

        if(!empty($id)){
            $list->where(['og.id|og.pid' => $id]);
        }

        if($state['type'] != '-999'){ // 订单类型
            $list->where(['o.type' => $state['type']]);
        }
        if(!empty($state['status'])){ // 订单状态
            if(in_array(8, $state['status'])){ // 退款
                $state['og.status'][] = '8-1';
                $state['og.status'][] = '8-2';
                $state['og.status'][] = '8-3';
            }
            if(in_array(9, $state['status'])) { // 换货
                $state['og.status'][] = '9-1';
                $state['og.status'][] = '9-2';
                $state['og.status'][] = '9-3';
                $state['og.status'][] = '9-4';
            }
            $list->whereIn('og.status', $state['status']);
        }
        if(!empty($state['username'])){ // 用户ID
            $list->where('u.username', 'like', '%' . trim($state['username']) . '%');
        }
        if(!empty($state['goods_and_brand'])){ // 商品品牌
            $list->where('g.name|b.name', 'like', '%' . trim($state['goods_and_brand']) . '%');
        }
        if(!empty($state['goods_name'])){ // 商品名称
            $list->where('g.name', 'like', '%' . $state['goods_name'] . '%');
        }
        if(!empty($state['place_order_time'])){ // 下单时间
            $start_time = strtotime(date('Y-m-d 00:00:00', strtotime($state['place_order_time'][0])));
            $end_time = strtotime(date('Y-m-d 23:59:59', strtotime($state['place_order_time'][1])));
            $list->whereBetween('o.place_order_time', [$start_time, $end_time]);
        }




        $list = $list->append(['status_text', 'purchase_price_text', 'price_text', 'supply_price_text', 'total_price_text'])
            ->order('og.order_id desc')
            ->select();

        $this->success('', [
            'list'   => $list,
            'total'  => count($list),
            'remark' => get_route_remark(),
        ]);
    }


    public function exportOrder(): void {
        $this->request->filter(['strip_tags', 'trim']);

        $field = "og.id, b.name brand_name, g.cover goods_cover, u.username, g.name goods_name,
                    og.color, og.size, g.supply_price, g.price, og.num, og.total_price, og.purchase_price, og.status, 
         og.id order_goods_id, og.pay_reserve_day, og.verbal_reserve_day, b.id brand_id, b.outstation_id";
        $where = [
            ['b.outstation_id', '=', $this->outstation['id']], // 只查询当前分站的订单
            ['o.status', '=', 1]
        ];
        $list = $this->orderGoodsModel->alias('og')
            ->with([
                'suborder_note' => function($query){ // 子订单备注
                    $query->with(['admin']);
                }, 'hasSubOrderGoods'
            ])->field($field) // 子订单
            ->leftJoin('order o', 'og.order_id = o.id') // 订单
            ->leftJoin('user u', 'o.user_id = u.id') // 用户
            ->leftJoin('goods g', 'og.goods_id = g.id') // 商品
            ->leftJoin('goods_brand b', 'g.goods_brand_id=b.id') //品牌
            ->where($where);

        $state = $this->request->param();

//        print_r($state);die;

        $id = $this->request->param('id');

        if(!empty($id)){
            $list->where(['og.id|og.pid' => $id]);
        }

        if($state['type'] != '-999'){ // 订单类型
            $list->where(['o.type' => $state['type']]);
        }
        if(!empty($state['status'])){ // 订单状态
            if(in_array(8, $state['status'])){ // 退款
                $state['og.status'][] = '8-1';
                $state['og.status'][] = '8-2';
                $state['og.status'][] = '8-3';
            }
            if(in_array(9, $state['status'])) { // 换货
                $state['og.status'][] = '9-1';
                $state['og.status'][] = '9-2';
                $state['og.status'][] = '9-3';
                $state['og.status'][] = '9-4';
            }
            $list->whereIn('og.status', $state['status']);
        }
        if(!empty($state['username'])){ // 用户ID
            $list->where('u.username', 'like', '%' . trim($state['username']) . '%');
        }
        if(!empty($state['goods_and_brand'])){ // 商品品牌
            $list->where('g.name|b.name', 'like', '%' . trim($state['goods_and_brand']) . '%');
        }
        if(!empty($state['goods_name'])){ // 商品名称
            $list->where('g.name', 'like', '%' . $state['goods_name'] . '%');
        }
        if(!empty($state['place_order_time'])){ // 下单时间
            $start_time = strtotime(date('Y-m-d 00:00:00', strtotime($state['place_order_time'][0])));
            $end_time = strtotime(date('Y-m-d 23:59:59', strtotime($state['place_order_time'][1])));
            $list->whereBetween('o.place_order_time', [$start_time, $end_time]);
        }


        $list = $list->append(['status_text', 'purchase_price_text', 'price_text', 'supply_price_text', 'total_price_text'])
            ->order('og.order_id desc')
            ->select();

        $date = date('Ymd');
        $path = Filesystem::fsFit(public_path() . 'storage/merge_order_export/' . $date);
        if(!is_dir($path)) Filesystem::mkdir($path);
        $file_name = '合并订单_' . date('Y_m_d H_i_s') . $this->auth->id . '.xlsx';
        $file_path = Filesystem::fsFit($path . '/' . $file_name);
        // 创建一个新的 Excel 对象
        $spreadsheet = new Spreadsheet();
        // 获取活动工作表
        $sheet = $spreadsheet->getActiveSheet();
        // 设置单元格的值
        $sheet->getRowDimension(1)->setRowHeight(30); // 设置行高
        $sheet->getColumnDimension('A')->setWidth(20); // 设置列宽
        $sheet->setCellValue('A1', '品牌名')->getStyle('A1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getColumnDimension('B')->setWidth(20); // 设置列宽
        $sheet->setCellValue('B1', '商品图')->getStyle('B1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getColumnDimension('C')->setWidth(20); // 设置列宽
        $sheet->setCellValue('C1', '客户名')->getStyle('C1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getColumnDimension('D')->setWidth(40); // 设置列宽
        $sheet->setCellValue('D1', '商品名')->getStyle('D1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getColumnDimension('E')->setWidth(10); // 设置列宽
        $sheet->setCellValue('E1', '颜色')->getStyle('E1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getColumnDimension('F')->setWidth(10); // 设置列宽
        $sheet->setCellValue('F1', '尺码')->getStyle('F1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getColumnDimension('G')->setWidth(10); // 设置列宽
        $sheet->setCellValue('G1', '品牌原价')->getStyle('G1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getColumnDimension('H')->setWidth(10); // 设置列宽
        $sheet->setCellValue('H1', '采购价格')->getStyle('H1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getColumnDimension('I')->setWidth(10); // 设置列宽
        $sheet->setCellValue('I1', 'DC价格')->getStyle('I1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getColumnDimension('J')->setWidth(10); // 设置列宽
        $sheet->setCellValue('J1', '数量')->getStyle('J1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getColumnDimension('K')->setWidth(10); // 设置列宽
        $sheet->setCellValue('K1', '总价')->getStyle('K1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getColumnDimension('L')->setWidth(20); // 设置列宽
        $sheet->setCellValue('L1', '出货状态')->getStyle('L1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);


        $row = 2;
        foreach($list as $val){
            $sheet->getRowDimension($row)->setRowHeight(60); // 设置行高
            // 品牌名
            $sheet->setCellValue('A' . $row, $val['brand_name'])->getStyle('A' . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
            // 商品图
            $drawing = new Drawing();
            $drawing->setPath(Filesystem::fsFit(public_path() . $val['goods_cover']));
            // 获取图片的尺寸
            $width = 50;
            $drawing->setCoordinates('B' . $row); // 图片要插入的单元格坐标
            $drawing->setOffsetX(45);
            $drawing->setOffsetY(5);
            $drawing->setWidth($width);
            // 将图片插入到单元格中
            $sheet->setCellValue('B' . $row, '');
            $drawing->setWorksheet($sheet);
            // 客户名
            $sheet->setCellValue('C' . $row, $val['username'])->getStyle('C' . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
            // 商品名
            $sheet->setCellValue('D' . $row, $val['goods_name'])->getStyle('D' . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
            // 颜色
            $sheet->setCellValue('E' . $row, $val['color'])->getStyle('E' . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
            // 尺码
            $sheet->setCellValue('F' . $row, $val['size'])->getStyle('F' . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
            // 品牌原价
            $sheet->setCellValue('G' . $row, $val['price_text'])->getStyle('G' . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
            // 采购价格
            $sheet->setCellValue('H' . $row, $val['supply_price_text'])->getStyle('H' . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
            // DC价格
            $sheet->setCellValue('I' . $row, $val['purchase_price_text'])->getStyle('I' . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
            // 数量
            $sheet->setCellValue('J' . $row, $val['num'])->getStyle('J' . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
            // 总价
            $sheet->setCellValue('K' . $row, $val['total_price_text'])->getStyle('K' . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
            // 出货状态
            $shipment_status = $val['status_text'];
            if($val['status'] == 3) $shipment_status .= $val['pay_reserve_day'] . '天';
            if($val['status'] == 4) $shipment_status .= $val['verbal_reserve_day'] . '天';
            $sheet->setCellValue('L' . $row, $shipment_status)->getStyle('L' . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
            $row++;
        }



        // 创建一个 Excel Writer 对象
        $writer = new Xlsx($spreadsheet);
        // 保存 Excel 文件
        $writer->save($file_path);


        $this->success('', [
            'file_url'   => '/storage/merge_order_export/' . $date . '/' . $file_name,
        ]);
    }




}